package com.yitong.xjd.controller;

import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yitong.xjd.domain.CustCreditRecord;
import com.yitong.xjd.domain.GuiZe;
import com.yitong.xjd.services.XinJinDaiService;

@Component
public class ZxbgParseUtils {
	@Autowired
	private XinJinDaiService xinJinDaiService;
	
	public CustCreditRecord getCustCreditRecord(String xmlstr){
		CustCreditRecord record=new CustCreditRecord();
		SimpleDateFormat yearSf=new SimpleDateFormat("yyyy");
		
		//读取xml字符串
		Element root = null;
		try {
			root = XmlParseUtils.getRootDocumengt(xmlstr);
		} catch (Exception e) {
			System.out.println("xml字符串接收转化为dom对象失败");
			e.printStackTrace();
		}
		
		//读取规则
		String gzPath=XmlParseUtils.class.getResource("").getPath();
		String guizePath=gzPath+"/xmlguize.xml";
		List<GuiZe> guizes = null;
		try {
			guizes = XmlParseUtils.getRulesFromLocalXml(guizePath);
		} catch (DocumentException e) {
			System.out.println("读取配置规则失败");
			e.printStackTrace();
			return null;
		}
		
		
		//身份证
		Element custIdtNo = null;
		try {
			custIdtNo = XmlParseUtils.getValueFromDocument(root, guizes,"custIdtNo");
			System.out.println("custIdtNo: " + custIdtNo.getTextTrim());
			record.setCustIdtNo(custIdtNo.getTextTrim());
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("解析身份证失败！");
			return null;
		}
		
		
		//年龄
		try {
			String custIdtno=custIdtNo.getTextTrim();
			int nowYear=Integer.parseInt(yearSf.format(new Date()));
			int bornyear=Integer.parseInt(custIdtno.substring(6, 10));
			System.out.println("custAge: "+(nowYear-bornyear));
			record.setCustAge((nowYear-bornyear)+"");
		} catch (Exception e) {
			System.out.println("计算年龄失败");
			record.setCustAge("0");
			e.printStackTrace();
		}
		
		
		//婚姻
		try {
			Element custMarr=XmlParseUtils.getValueFromDocument(root,guizes,"custMarr");
			System.out.println("custMarr: "+custMarr.getTextTrim());
			record.setCustMarr(custMarr.getTextTrim());
		} catch (Exception e1) {
			System.out.println("解析婚姻状况失败！");
			record.setCustMarr("未知");
			e1.printStackTrace();
		}
		
		
		//学历
		try {
			Element custEndu=XmlParseUtils.getValueFromDocument(root,guizes,"custEndu");
			System.out.println("custEndu: "+custEndu.getTextTrim());
			record.setCustEndu(custEndu.getTextTrim());
		} catch (Exception e1) {
			System.out.println("解析学历失败！");
			record.setCustEndu("未知");
			e1.printStackTrace();
		}
		
		
		//职称
		try {
			Element custTitl=XmlParseUtils.getValueFromDocument(root,guizes,"custTitl");
			System.out.println("custTitl: "+custTitl.getTextTrim());
			record.setCustTitl(custTitl.getTextTrim());
		} catch (Exception e1) {
			System.out.println("职务解析失败！");
			record.setCustEndu("未知");
			e1.printStackTrace();
		}
		
		
		//户籍
		try {
			Element custRegistAdd=XmlParseUtils.getValueFromDocument(root,guizes,"custRegistAdd");
			String custRegistAddStr=custRegistAdd.getTextTrim();
			System.out.println("custRegistAdd: "+custRegistAddStr);
			if(custRegistAddStr!=null&&(
					custRegistAddStr.indexOf("西安市")!=-1
					||custRegistAddStr.indexOf("雁塔区")!=-1
					||custRegistAddStr.indexOf("未央区")!=-1
					||custRegistAddStr.indexOf("碑林区")!=-1
					||custRegistAddStr.indexOf("莲湖区")!=-1
					||custRegistAddStr.indexOf("长安区")!=-1
					||custRegistAddStr.indexOf("新城区")!=-1
					||custRegistAddStr.indexOf("灞桥区")!=-1
					||custRegistAddStr.indexOf("高陵区")!=-1
					||custRegistAddStr.indexOf("临潼区")!=-1
					||custRegistAddStr.indexOf("阎良区")!=-1
					||custRegistAddStr.indexOf("户县")!=-1
					||custRegistAddStr.indexOf("蓝田")!=-1
					||custRegistAddStr.indexOf("周至")!=-1)){
				record.setCustRegistAdd("本地户籍");
			}else{
				record.setCustRegistAdd("外地户籍");
			}
		} catch (Exception e1) {
			System.out.println("解析户籍所在地失败");
			record.setCustRegistAdd("外地户籍");
			e1.printStackTrace();
		}
		
		
		//征信查询次数
		try {
			Element custQueryCntTr=XmlParseUtils.getValueFromDocument(root,guizes,"custQueryCnt");
			List<Element> custQueryCntTds=XmlParseUtils.getCondElements(custQueryCntTr, "td_lasts3");
			int custQueryCount=0;
			for(Element elm:custQueryCntTds){
				Element span=XmlParseUtils.getElement(elm, "div@font@span");
				int n=Integer.parseInt(span.getTextTrim());
				custQueryCount+=n;
			}
			System.out.println("custQueryCnt : "+custQueryCount);
			record.setCustQueryCnt(custQueryCount+"");
		} catch (Exception e1) {
			System.out.println("解析征信查询次数失败");
			record.setCustQueryCnt("0");
			e1.printStackTrace();
		}
		
		
		//信用状况 
		int custCreditcount=0;
		String lianXuThree="0";
		try {
			Element custCreditTbody=XmlParseUtils.getValueFromDocument(root,guizes,"custCredit1");
			List<Element> custCreditTrs=XmlParseUtils.getCondElements(custCreditTbody, "tr_likes([0-9]{4}年[0-9]{2}月-[0-9]{4}年[0-9]{2}月的还款记录)");
			for(Element trRoot:custCreditTrs){
				Element tr=XmlParseUtils.getValueFromDocument(trRoot,guizes,"custCredit2");
				List<Element> custCreditTds=XmlParseUtils.getCondElements(tr, "td_firsts");
				int lianXuCount=0;
				for(Element el:custCreditTds){
					Element span=XmlParseUtils.getElement(el, "div@font@span");
					String sv=span.getTextTrim();
					if(sv.matches("[0-9]{1,2}")){
						custCreditcount+=1;
						lianXuCount+=1;
					}else{
						lianXuCount=0;
					}
				}
				if(lianXuCount>=3){
					lianXuThree="1";
				}
			}
			System.out.println("custCredit1: "+custCreditcount);
		}catch (Exception e1) {
			e1.printStackTrace();
		}
		record.setCustCredit(custCreditcount+"");
		
		
		
		//连三累六
		if(custCreditcount>=6||lianXuThree.equals("1")){
			record.setYuqiFlag("1");
		}else{
			record.setYuqiFlag("0");
		}
			
			
			
		//已用授信/授信总额
		try {
			//已用授信
			Element custValidCreditUsedSpan=XmlParseUtils.getValueFromDocument(root,guizes,"custValidCreditUsed");
			System.out.println("custValidCreditUsed : "+custValidCreditUsedSpan.getTextTrim());
			String custValidCreditUsed=custValidCreditUsedSpan.getTextTrim();
			//授信总额
			Element custValidCreditTotalSpan=XmlParseUtils.getValueFromDocument(root,guizes,"custValidCreditTotal");
			System.out.println("custValidCreditTotal : "+custValidCreditTotalSpan.getTextTrim());
			String custValidCreditTotal=custValidCreditTotalSpan.getTextTrim();
			//计算占比
			double rato=Double.parseDouble(custValidCreditUsed.replace(",",""))/Double.parseDouble(custValidCreditTotal.replace(",",""));
			NumberFormat nt=NumberFormat.getPercentInstance();
			nt.setMinimumFractionDigits(0);
			System.out.println("custValidCredit : "+nt.format(rato));
			//设置占比
			record.setCustValidCredit(nt.format(rato));
		} catch (Exception e1) {
			System.out.println("解析授信使用占比失败");
			record.setCustValidCredit("0%");
			e1.printStackTrace();
		}
		
		
		//未结清贷款余额占工资比重
		try {
			Element custLongBalFont=XmlParseUtils.getValueFromDocument(root,guizes,"custLongBal");
			String custLongBal=custLongBalFont.getTextTrim().replace(",","");
			System.out.println("custLongBal:"+custLongBal);
			//查询月平均工资
			String monthBal=xinJinDaiService.queryCustMonthBal(record.getCustIdtNo());
			System.out.println("monthSalary: "+monthBal);
			//计算占比
			double rato=Double.parseDouble(custLongBal)/Double.parseDouble(monthBal);
			NumberFormat nt=NumberFormat.getPercentInstance();
			nt.setMinimumFractionDigits(0);
			
			System.out.println("custLongBalRato : "+nt.format(rato));
			record.setCustLongBal(nt.format(rato));
		} catch (Exception e1) {
			e1.printStackTrace();
			System.out.println("解析未结清贷款余额占工资比重失败");
			record.setCustLongBal("0%");
		}
		
		
		//查询日期
		String querydate = null;
		try {
			Element queryDateElement=XmlParseUtils.getValueFromDocument(root,guizes,"queryDate");
			String querydateStr=queryDateElement.getTextTrim();
			querydate = getRegexString("[0-9]{4}.[0-9]{2}.[0-9]{2}",querydateStr).replace(".","-");
			System.out.println("queryDate: "+querydate);
			record.setQueryDate(querydate);
		} catch (Exception e1) {
			System.out.println("解析查询日期失败");
			record.setQueryDate("");
			e1.printStackTrace();
		}
		
		//失效日期
		//输入日期
		
		return record;
	}

	//返回正则匹配的第一个字符串
	public static String getRegexString(String reg,String source){
		List<String> result=new ArrayList<String>();
		Pattern p=Pattern.compile(reg);
		Matcher m=p.matcher(source);
		while(m.find()){
			result.add(m.group());
		}
		if(result.size()>0){
			return (String)result.get(0);
		}else{
			return null;
		}
	}
}
